import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react'
import {
  Layout,
  Input,
  Button,
  message,
  Alert,
  Switch,
  Space,
  Select,
  notification,
  Popover,
  Divider,
  SelectProps,
  Modal,
} from 'antd'
import { EventsOn, EventsOff } from '../../../wailsjs/runtime'
import {
  ConnectSSH,
  DisconnectSSH,
  StartLogStream,
  StopLogStream,
  GetConnectedSSHHost,
  GetHostInfo,
  CheckCmdIsContinuous,
  DeleteSSHHost,
} from '../../../wailsjs/go/main/App'
import Editor from 'react-simple-code-editor'
import { highlight, languages } from 'prismjs'
import 'prismjs/components/prism-clike'
import 'prismjs/components/prism-javascript'
import 'prismjs/themes/prism-tomorrow.css'
import './index.scss'
import 'xterm/css/xterm.css'
import type { GetProps } from 'antd'
import init, { filter_logs } from '../../../public/log_filter.js'
import { escapeRegExp, HandleStrings } from '../../utils'
import QueryRules from '../../eums'
import { DeleteOutlined } from '@ant-design/icons'
import { splitStringAndHandle } from './utils'
import CheckHostsAliveButton from './components/ButtonAlive'
import SearchComponent from './components/Search'

const { Content } = Layout

type SearchProps = GetProps<typeof Input.Search>

interface SSHConfig {
  username: string
  password: string
  host: string
  port: number
  command: string
  stream: boolean
}

// 自定义日志高亮规则
languages.log = {
  keyword: {
    pattern:
      /\[ERROR\]|\|.*ERROR.*\||\[INFO\]|\|.*INFO.*\||\[DEBUG\]|\|.*DEBUG.*\||\[WARNING\]|\|.*WARNING.*\|/g,
    alias: 'keyword',
  },
  string: {
    pattern: /".*?"/g,
    alias: 'string',
  },
  number: {
    pattern: /\b\d+\b/g,
    alias: 'number',
  },
}

// 查询配置
const options: SelectProps['options'] = [
  {
    label: '去除前后空格',
    value: 1,
  },
  {
    label: '忽略大小写',
    value: 2,
  },
]

const SSHComponent: React.FC = () => {
  const [SSHConfig, setSSHConfig] = useState<SSHConfig>({
    username: 'root',
    password: 'Dell@123',
    host: '192.100.8.26',
    port: 22,
    command: 'docker ps',
    stream: false,
  })

  // 初始化
  const [logs, setLogs] = useState<string[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [isStreaming, setIsStreaming] = useState(false)
  const [connect, setConnect] = useState(false)
  const [selectedRule, setSelectedRule] = useState<QueryRules[]>([])
  const [store, setStore] = useState<boolean>(false)
  const [hostportList, SetHostPortList] = useState<string[]>([])
  // 是否过滤检索内容
  const [filtered, setFiltered] = useState<boolean>(true)
  // 是否启动流
  const [enableStream, setEnableStream] = useState<boolean>(false)

  // Add these state variables to your component
  const [aliveStatus, setAliveStatus] = useState<Record<string, boolean>>({})

  // 绑定dom元素
  const editorRef = useRef(null)
  const searchRef = useRef(null)
  const executeBtnRef = useRef(null)

  // 监听后端推送的日志
  useEffect(() => {
    // 注册事件监听器
    const logListener = (logLine: string) => {
      setLogs((prevLogs) => [...prevLogs, logLine])
    }

    const errorListener = (errorMessage: string) => {
      setError(errorMessage)
      setIsStreaming(false)
    }

    const commandEndListener = (endMessage: string) => {
      setIsStreaming(false)
      message.info(endMessage)
    }

    // 注册事件
    EventsOn('log', logListener)
    EventsOn('error', errorListener)
    EventsOn('command-end', commandEndListener)

    // 清理函数：组件卸载时移除事件监听器
    return () => {
      console.log('清理事件监听器...')
      EventsOff('log', 'error', 'command-end')
    }
  }, [])

  // 清理状态
  const clearState = () => {
    setLogs([])
    setSearchTerm('')
    setError(null)
  }

  const handleConnect = () => {
    message.loading('正在连接...', 0)
    ConnectSSH(
      SSHConfig.username,
      SSHConfig.password,
      SSHConfig.host,
      SSHConfig.port,
      store,
    )
      .then(() => {
        setConnect(true)
        message.destroy()
        message.success('服务已建立')
      })
      .catch((error) => {
        console.error('handleConnect ~ error:', error)
        message.destroy()
        message.error('连接失败')
      })
  }

  const handleDisconnect = () => {
    // 如果正在流式传输，先停止
    if (isStreaming) {
      message.warning('正在流式传输中, 请先终止流式传输')
      return
    }

    DisconnectSSH()
      .then(() => {
        setConnect(false)
        clearState()
        setIsStreaming(false)
        message.success('服务已断开')
      })
      .catch((error) => {
        console.error('handleDisconnect ~ error:', error)
        message.error('断开连接失败')
      })
  }

  // 历史命令管理
  const [commandHistory, setCommandHistory] = useState<string[]>([])
  const [showCommandHistory, setShowCommandHistory] = useState(false)
  const [filteredHistory, setFilteredHistory] = useState<string[]>([])
  const commandInputRef = useRef<any>(null)
  const historyDropdownRef = useRef<HTMLDivElement>(null)

  // 加载历史命令
  useEffect(() => {
    const savedCommands = localStorage.getItem('sshCommandHistory')
    if (savedCommands) {
      try {
        const parsedCommands = JSON.parse(savedCommands)
        setCommandHistory(Array.isArray(parsedCommands) ? parsedCommands : [])
      } catch (e) {
        console.error('Failed to parse command history:', e)
        setCommandHistory([])
      }
    }
  }, [])

  // 保存命令到历史记录
  const saveCommandToHistory = (command: string) => {
    if (!command.trim()) return

    const newHistory = [
      command,
      ...commandHistory.filter((cmd) => cmd !== command),
    ].slice(0, 50) // 限制历史记录数量为50条

    setCommandHistory(newHistory)
    localStorage.setItem('sshCommandHistory', JSON.stringify(newHistory))
  }

  // 过滤历史命令
  useEffect(() => {
    if (SSHConfig.command.trim() === '') {
      setFilteredHistory(commandHistory)
    } else {
      setFilteredHistory(
        commandHistory.filter((cmd) =>
          cmd.toLowerCase().includes(SSHConfig.command.toLowerCase()),
        ),
      )
    }
  }, [SSHConfig.command, commandHistory])

  // 点击外部关闭历史命令下拉框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        historyDropdownRef.current &&
        !historyDropdownRef.current.contains(event.target as Node) &&
        commandInputRef.current
      ) {
        // 检查点击的元素是否在Input组件内部
        const inputElement = commandInputRef.current.input
        if (inputElement && !inputElement.contains(event.target as Node)) {
          setShowCommandHistory(false)
        }
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])

  // 处理表单提交
  const handleSubmit = () => {
    if (!connect) {
      message.error('请先建立连接')
      return
    }

    clearState()
    setIsStreaming(true)

    const _start_log_stream = (command: string, stream: boolean) => {
      StartLogStream(command, stream)
        .then(() => {
          if (stream) {
            message.success('流式传输已启动')
          }
        })
        .catch((error) => {
          console.error('handleSubmit ~ error:', error)
          if (stream) {
            message.success('流式传输启动失败')
          } else {
            message.error('命令执行失败')
          }
        })
    }

    // 将命令添加到历史记录中
    saveCommandToHistory(SSHConfig.command)

    // 隐藏历史命令下拉框
    setShowCommandHistory(false)

    // 调用后端函数
    // 检查命令是否是可持续命令
    CheckCmdIsContinuous(SSHConfig.command)
      .then((res: boolean) => {
        console.log('CheckCmdIsContinuous ~ res:', res)
        if (res === true) {
          setEnableStream(true)
          SSHConfig.stream = true
        }
        _start_log_stream(SSHConfig.command, SSHConfig.stream)
      })
      .catch((error) => {
        console.error('CheckCmdIsContinuous ~ error:', error)
        _start_log_stream(SSHConfig.command, SSHConfig.stream)
      })
  }

  // 处理停止按钮点击
  const handleStop = () => {
    // 将流按钮关闭
    setEnableStream(false)
    StopLogStream()
      .then(() => {
        message.success('流式传输已停止')
        setIsStreaming(false)

        // 关闭流式传输flag
        setSSHConfig({
          ...SSHConfig,
          stream: false,
        })
      })
      .catch((error) => {
        console.error('handleStop ~ error:', error)
        message.error('流式传输停止失败')
      })
  }

  const [filteredLogs, setFilteredLogs] = useState<string[]>([])
  useEffect(() => {
    // 加载 Wasm 模块
    if (logs.length > 0) {
      const wasm_s = performance.now()
      init()
        .then(() => {
          const start = performance.now()
          console.log('rules: ', selectedRule)
          const rules = selectedRule.map((rule) => rule.valueOf())

          let filtered_logs: string[] = []
          if (filtered) {
            // 将日志检索字符串以逗号分隔，并转换为字符串数组
            const searchTerms = searchTerm.split(',')
            filtered_logs = filter_logs(
              logs,
              searchTerms,
              new Int32Array(rules),
            )
          } else {
            filtered_logs = logs
          }
          const end = performance.now()

          const time_duration = end - start
          console.log(`filtered_logs, time cost: ${time_duration} ms`)
          setFilteredLogs(filtered_logs)

          if (time_duration >= 1000) {
            message.error(
              `日志过滤耗时过长 - ${time_duration}ms...请查看终端日志`,
            )
            console.log(
              '========================== Slow Contents =========================',
            )
            console.warn(logs)
            console.log(
              '==================================================================',
            )
          }
        })
        .catch((error) => {
          console.error('Failed to load Wasm module:', error)
        })

      const wasm_e = performance.now()
      console.log(`wasm load cost time: ${wasm_e - wasm_s} ms`)
    } else {
      // 清空日志
      setFilteredLogs([])
    }
  }, [logs, searchTerm, selectedRule, filtered])

  const onSearch: SearchProps['onSearch'] = (value, _e) => {
    // 清除前后空格
    const value_ = new HandleStrings(value, selectedRule).handle()
    console.log('after value_:', value_, 'before:', value)

    // 设置搜索词并打印日志，帮助调试
    setSearchTerm(value_)
    console.log(
      '搜索词设置为:',
      value_,
      '过滤后的日志数量:',
      filteredLogs?.length,
    )
  }

  const logsToString = useMemo(() => {
    return filteredLogs.join('\n')
  }, [filteredLogs])

  // 高亮显示日志
  const escapeHTML = (str: string) =>
    str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&apos;')

  // 高亮代码
  const [highlightedCode, setHighlightedCode] = useState('') // 高亮后的代码
  const highlightWithSearch = (code: string, searchTerms: string[]) => {
    // 通过异步优化渲染的逻辑
    return new Promise<string>((resolve) => {
      setTimeout(() => {
        let highlightedCode_ = highlight(code, languages.log, 'log')

        if (
          searchTerms.length === 0 ||
          (searchTerms.length === 1 && searchTerms[0].trim() === '')
        ) {
          resolve(highlightedCode_)
          return
        }

        // 为每个搜索词应用高亮，使用不同的背景色
        const colors = [
          'yellow',
          '#FFCCCB', // 浅红色
          '#CCFFCC', // 浅绿色
          '#CCCCFF', // 浅蓝色
          '#FFFFCC', // 浅黄色
          '#FFCCFF', // 浅紫色
          '#CCFFFF', // 浅青色
        ]

        searchTerms.forEach((searchTerm_, index) => {
          if (searchTerm_.trim() === '') return // 跳过空搜索词
          // 为每个搜索词选择一个颜色
          const color = colors[index % colors.length]

          // 转义搜索词以避免正则表达式中的特殊字符干扰
          const escapedSearchTerm = escapeRegExp(searchTerm_)

          // 创建一个不区分大小写的正则表达式
          const regex = new RegExp(`(${escapedSearchTerm})`, 'gi')

          // 替换匹配项，添加带有特定颜色的高亮样式
          highlightedCode_ = highlightedCode_.replace(
            regex,
            (match) =>
              `<span style="background-color: ${color}; font-weight: bold;">${escapeHTML(match)}</span>`,
          )
        })

        resolve(highlightedCode_)
      }, 0)
    })
  }

  useEffect(() => {
    const searchTerms = splitStringAndHandle(searchTerm, ',', selectedRule)
    highlightWithSearch(logsToString, searchTerms).then(setHighlightedCode)
  }, [logsToString, searchTerm, selectedRule])

  // 选择查询规则
  const handleOptionChange = (value: number[]) => {
    setSelectedRule(value)
  }

  // notification
  const [api, contextHolder] = notification.useNotification()
  const openNotification = () => {
    api.info({
      duration: 3,
      message: '填充历史数据',
      description: `${JSON.stringify({
        username: SSHConfig.username,
        password: SSHConfig.password,
        host: SSHConfig.host,
        port: SSHConfig.port,
      })}`,
      style: {
        textAlign: 'left',
      },
      onClick: () => {
        console.log('The auto-filled data:', SSHConfig)
      },
      placement: 'bottomRight',
    })
  }

  // Update the renderHostList function to include scrolling container
  const renderHostList = useCallback(() => {
    // If there are no hosts, show a message
    if (hostportList.length === 0) {
      return <div style={{ padding: '8px 0' }}>暂无保存的主机记录</div>
    }

    return (
      <div>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '0 4px 8px 4px',
            borderBottom: '1px solid #f0f0f0',
            marginBottom: '8px',
          }}
        >
          <span style={{ fontSize: '12px', color: '#8c8c8c' }}>
            共 {hostportList.length} 条记录
          </span>
          <CheckHostsAliveButton
            hostportList={hostportList}
            onStatusChange={setAliveStatus}
          />
        </div>
        <div
          className="custom-scrollbar"
          style={{
            maxHeight: '300px', // Set maximum height
            overflowY: 'auto', // Enable vertical scrolling
            width: '200px', // Set a fixed width for the popover content
            msOverflowStyle: 'none',
            scrollbarWidth: 'none',
          }}
        >
          {hostportList.map((hostport, index) => (
            <div
              className="host-list-item"
              key={index}
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '8px',
                padding: '6px 8px',
                borderRadius: '4px',
                transition: 'background-color 0.3s',
                cursor: 'pointer',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.backgroundColor = '#f5f5f5'
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = 'transparent'
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span
                  style={{
                    width: '8px',
                    height: '8px',
                    borderRadius: '50%',
                    backgroundColor: aliveStatus[hostport]
                      ? '#52c41a' // 绿色
                      : '#ff4d4f', // 红色
                    marginRight: '8px',
                    display: 'inline-block',
                  }}
                />
                <p
                  style={{ cursor: 'pointer', margin: 0 }}
                  onClick={async (e) => {
                    e.stopPropagation()
                    const [host, port] = hostport.split(':')
                    await autofillSSHConfig(host, Number(port))
                  }}
                >
                  {hostport}
                </p>
              </div>
              <Button
                type="text"
                icon={<DeleteOutlined />}
                className="delete-host-btn"
                style={{
                  backgroundColor: '#f5f5f5', // 浅灰色背景
                  borderRadius: '50%', // 圆形按钮
                  width: '24px', // 固定宽度
                  height: '24px', // 固定高度
                  display: 'flex',
                  justifyContent: 'center',
                  alignItems: 'center',
                  border: 'none', // 移除边框
                  opacity: 0.8, // 稍微透明
                  color: '#8c8c8c',
                  transition: 'all 0.3s', // 添加过渡效果
                }}
                size="small"
                onClick={(e) => {
                  e.stopPropagation()
                  const [host, port] = hostport.split(':')
                  // Show a confirmation before deleting
                  Modal.confirm({
                    title: '确认删除',
                    content: `确定要删除主机记录 ${hostport} 吗？`,
                    okText: '确认',
                    cancelText: '取消',
                    onOk: () => deleteHostRecord(host, Number(port)),
                  })
                }}
              />
            </div>
          ))}
        </div>
      </div>
    )
  }, [hostportList, aliveStatus])

  const autofillSSHConfig = async (host: string, port: number) => {
    console.log('autofillSSHConfig......................')
    if (host && port) {
      const store_data = await GetHostInfo(host, port)
      if (Object.keys(store_data).length > 0) {
        openNotification()
        setSSHConfig({
          ...SSHConfig,
          host: host,
          username: store_data.username,
          port: port,
          password: store_data.password,
        })
      }
    }
  }

  // 获取hostport列表
  const getHostportList = useCallback(async () => {
    const hostportList_ = await GetConnectedSSHHost()
    console.log('hostportList_:', hostportList_)
    SetHostPortList(hostportList_)
  }, [])

  // 滚动条自动滚动
  useEffect(() => {
    // 在 items 更新后滚动到底部
    setTimeout(() => {
      if (editorRef.current) {
        ;(editorRef.current as HTMLElement).scrollTop = (
          editorRef.current as HTMLElement
        ).scrollHeight
      }
    }, 50)
  }, [logs])

  // 监听键盘事件, 所有的键盘事件都在这里
  useEffect(() => {
    const handleKeyDownWrapper = (event: KeyboardEvent) => handleKeyDown(event)
    window.addEventListener('keydown', handleKeyDownWrapper)
    return () => {
      console.log('清理Keyboard事件监听器...')
      window.removeEventListener('keydown', handleKeyDownWrapper)
    }
  }, [connect])

  // 键盘事件处理函数
  const handleKeyDown = (event: KeyboardEvent) => {
    switch (event.key.toLowerCase()) {
      case 'f':
        // 按下 Ctrl + F 组合键，打开搜索框
        if (event.ctrlKey) {
          if (searchRef.current) {
            message.open({
              content: '🤔请在文本检索框输入搜索内容',
              key: 'search',
            })
            ;(searchRef.current as HTMLElement).focus()
          }
        }
        break
      case 'enter':
        // 按下 Ctrl + Enter 键，执行ssh命令操作
        if (event.ctrlKey) {
          // 执行ssh命令操作
          if (
            executeBtnRef.current &&
            !(executeBtnRef.current as HTMLButtonElement).disabled &&
            connect &&
            SSHConfig.command.trim() &&
            !(isStreaming && SSHConfig.stream)
          ) {
            message.open({
              content: '💻开始执行命令',
              key: 'execute',
            })
            ;(executeBtnRef.current as HTMLElement).click()
          }
        }
        break
      default:
        console.warn(`Unsupported key: ${event.key}`)
        break
    }
  }

  // Add this function to delete a host record - place it near the other SSH-related functions
  const deleteHostRecord = async (host: string, port: number) => {
    try {
      // You'll need to implement this function in your Go backend
      await DeleteSSHHost(host, port)
      message.success(`已删除主机记录 ${host}:${port}`)
      // Refresh the host list after deletion
      getHostportList()
    } catch (error) {
      console.error('Failed to delete host record:', error)
      message.error('删除主机记录失败')
    }
  }

  return (
    <>
      {contextHolder}
      <Content className="body-area">
        <div className="input_form">
          {/* 表单输入区域 */}
          <Space
            id="ssh_form"
            direction="vertical"
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexDirection: 'row',
              columnGap: '10px',
              padding: '10px 0',
              marginLeft: '28px',
            }}
          >
            <span className="input_area" id="host">
              <label htmlFor="">主机:</label>
              <Popover
                title={
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                    }}
                  >
                    <span>主机列表</span>
                  </div>
                }
                trigger="click"
                content={renderHostList}
                // open={!connect && clicked && hostportList.length > 0}
              >
                <Input
                  name="host"
                  placeholder="Host"
                  value={SSHConfig.host}
                  disabled={connect}
                  onClick={getHostportList}
                  onChange={(e) =>
                    setSSHConfig({ ...SSHConfig, host: e.target.value })
                  }
                  autoComplete="host"
                />
              </Popover>
            </span>
            <span className="input_area" id="port">
              <label htmlFor="">端口:</label>
              <Input
                placeholder="Port"
                type="number"
                name="port"
                autoComplete="port"
                value={SSHConfig.port}
                disabled={connect}
                onChange={(e) =>
                  setSSHConfig({
                    ...SSHConfig,
                    port: parseInt(e.target.value),
                  })
                }
              />
            </span>
            <span className="input_area" id="username">
              <label htmlFor="">用户名:</label>
              <Input
                placeholder="Username"
                name="username"
                autoComplete="username"
                value={SSHConfig.username}
                disabled={connect}
                onChange={(e) =>
                  setSSHConfig({ ...SSHConfig, username: e.target.value })
                }
              />
            </span>
            <span className="input_area" id="password">
              <label htmlFor="">密码:</label>
              <Input
                placeholder="Password"
                name="password"
                autoComplete="password"
                type="password"
                value={SSHConfig.password}
                disabled={connect}
                onChange={(e) =>
                  setSSHConfig({ ...SSHConfig, password: e.target.value })
                }
                onClick={async () => {
                  await autofillSSHConfig(SSHConfig.host, SSHConfig.port)
                }}
              />
            </span>
            <span className="input_area" id="store">
              <label htmlFor="">存储:</label>
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                disabled={connect}
                defaultChecked={false}
                onClick={(checked: boolean) => {
                  setStore(checked)
                }}
              />
            </span>
            {connect && (
              <Button type="primary" onClick={handleDisconnect} danger>
                断开
              </Button>
            )}
            {!connect && (
              <Button type="primary" onClick={handleConnect}>
                连接
              </Button>
            )}
          </Space>
          <div
            id="command"
            style={{
              marginBottom: '10px',
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
            }}
          >
            <label htmlFor="">shell命令:</label>
            <div className="command">
              <div className="command-input-container">
                <Input
                  ref={commandInputRef}
                  placeholder="Command"
                  value={SSHConfig.command}
                  onChange={(e) => {
                    setSSHConfig({ ...SSHConfig, command: e.target.value })
                    setShowCommandHistory(true)
                  }}
                  onFocus={() => {
                    console.log(
                      'Input focused, showing history',
                      commandHistory,
                    )
                    setShowCommandHistory(true)
                  }}
                  onClick={() => {
                    console.log(
                      'Input clicked, showing history',
                      commandHistory,
                    )
                    setShowCommandHistory(true)
                  }}
                  allowClear
                />
                {showCommandHistory && (
                  <div
                    className="command-history-dropdown"
                    ref={historyDropdownRef}
                  >
                    {filteredHistory.length > 0 ? (
                      filteredHistory.map((cmd, index) => (
                        <div
                          key={index}
                          className="command-history-item"
                          onClick={() => {
                            setSSHConfig({ ...SSHConfig, command: cmd })
                            setShowCommandHistory(false)
                          }}
                        >
                          {cmd}
                        </div>
                      ))
                    ) : (
                      <div className="command-history-item command-history-empty">
                        暂无历史命令
                      </div>
                    )}
                  </div>
                )}
              </div>
              <div className="switch">
                <label htmlFor="stream">流:</label>
                <Switch
                  checkedChildren="是"
                  unCheckedChildren="否"
                  defaultChecked={false}
                  checked={enableStream}
                  onChange={(checked: boolean) => {
                    setEnableStream(checked)
                  }}
                  onClick={(checked: boolean) => {
                    if (isStreaming) {
                      message.warning('流已开启，请先停止流')
                      return
                    }
                    // 根据switch状态设置: SSHConfig.stream
                    setSSHConfig({ ...SSHConfig, stream: checked })
                  }}
                />
              </div>
              <Button
                ref={executeBtnRef}
                type="primary"
                onClick={handleSubmit}
                // loading={isStreaming}
                disabled={isStreaming && SSHConfig.stream}
                style={{ margin: '0 5px 0 0' }}
              >
                执行
              </Button>
              <Button
                type="default"
                onClick={handleStop}
                disabled={!isStreaming}
                style={{ margin: '0 0 0 5px' }}
              >
                中止
              </Button>
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <Alert
              message={error}
              type="error"
              showIcon
              style={{ marginBottom: '24px' }}
              closable
            />
          )}

          {/* 日志检索框 */}
          <div
            className="input_area"
            style={{
              margin: '10px 0',
              justifyContent: 'space-between',
              flexWrap: 'wrap',
              gap: '8px',
            }}
          >
            <div
              className="search-controls"
              style={{
                display: 'flex',
                alignItems: 'center',
                flexWrap: 'wrap',
                flex: '1',
              }}
            >
              <label htmlFor="">文本检索:</label>
              <SearchComponent
                onSearch={onSearch}
                setSearchTerm={setSearchTerm}
                searchRef={searchRef}
              />
              <span className="filter_area" id="filter">
                <label htmlFor="">过滤:</label>
                <Switch
                  checkedChildren="是"
                  unCheckedChildren="否"
                  defaultChecked={filtered}
                  onClick={(checked: boolean) => {
                    setFiltered(checked)
                  }}
                />
              </span>
              <Select
                style={{ width: '150px', marginRight: '10px' }}
                mode="multiple"
                placeholder="字符串处理规则"
                onChange={handleOptionChange}
                options={options}
                maxTagCount="responsive"
                allowClear
              />
              <Divider
                type="vertical"
                style={{
                  borderColor: '#7cb305',
                  marginRight: '18px',
                  height: '20px',
                }}
              />
              <Button type="default" onClick={() => setLogs([])}>
                清空日志
              </Button>
            </div>

            {searchTerm && (
              <div
                className="search-result-container"
                style={{ display: 'flex', alignItems: 'center' }}
              >
                <label htmlFor="">结果:</label>
                <span className="search-result-count">
                  找到 <strong>{filteredLogs.length}</strong> 条结果
                </span>
              </div>
            )}
          </div>
        </div>

        {/* 日志展示区域 */}
        <div id="editor-log" ref={editorRef}>
          {/* <div className="title-bar">
              <div className="button red"></div>
              <div className="button yellow"></div>
              <div className="button green"></div>
            </div> */}
          <Editor
            id="editor-body"
            value={logsToString}
            onValueChange={() => {}}
            highlight={() => highlightedCode}
            padding={10}
            style={{
              fontFamily: '"Fira code", "Fira Mono", monospace',
              fontSize: 13,
              background: '#f9f9f9',
              border: '1px solid #ccc',
              minHeight: '100%',
              overflowY: 'scroll',
              marginRight: '-10px',
              overflowX: 'hidden',
              whiteSpace: 'pre-wrap',
            }}
          />
        </div>
      </Content>
    </>
  )
}

export default SSHComponent
